<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    :title="vdata.isAdd ? '新增二维码' : '修改二维码' "
    width="46%"
    @close="onClose"
  >
    <a-form v-if="vdata.visible" ref="infoFormModel" :model="vdata.saveObject" :rules="saveRule">
      <a-row v-if="vdata.isAdd">
        <a-form-item label="批次号" name="batchId">
          <a-input-number v-model:value="vdata.saveObject.batchId" style="width:70%; margin-right: 20px;" /> 
          <a-button type="primary" size="small" @click="resetBatchId">今天</a-button>
          <p class="jeepay-tip-text">( 数字格式， 二维码编号的前缀， 建议采用： YYMMDD+次数表示 )</p>
        </a-form-item>
      </a-row>

      <a-row v-if="vdata.isAdd">
        <a-form-item label="创建数量" name="addNum">
          <a-input-number v-model:value="vdata.saveObject.addNum" />
        </a-form-item>
      </a-row>

      <a-row v-if="vdata.isAdd">
        <a-form-item label="二维码模板" name="qrcShellId">
          <a-select v-model:value="vdata.saveObject.qrcShellId" placeholder="选择模板" style="width: 200px;">
            <a-select-option value="">无</a-select-option>
            <template v-for="item in vdata.qrcShellList" :key="item.sid">
              <a-select-option :value="item.sid">{{ item.shellAlias }} <img :src="item.shellImgViewUrl" style="width: 20px"> </a-select-option>
            </template>
          </a-select>
        </a-form-item>
      </a-row>

      <a-row>
        <a-form-item label="状态" name="qrcState">
          <a-radio-group v-model:value="vdata.saveObject.qrcState">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-row>

      <a-row>
        <a-form-item label="二维码金额" name="fixedFlag">
          <a-radio-group v-model:value="vdata.saveObject.fixedFlag">
            <a-radio :value="0">任意金额</a-radio>
            <a-radio :value="1">固定金额</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="vdata.saveObject.fixedFlag" label="" name="fixedPayAmount">
          <a-input-number v-model:value="vdata.saveObject.fixedPayAmount" :precision="2" style="width: 130px" /> 元
        </a-form-item>
      </a-row>

      <a-row>
        <a-form-item v-if="vdata.isAdd" label="扫码后页面类型" name="entryPage">
          <a-radio-group v-model:value="vdata.saveObject.entryPage" @change="clearUrlPlaceholder()">
            <a-radio :value="'default'">默认</a-radio>
            <a-radio :value="'h5'">固定H5页面</a-radio>
            <a-radio :value="'lite'">固定小程序页面</a-radio>
          </a-radio-group>
        </a-form-item>
        <div style="margin-left: 110px;margin-top: -50px;"><br><p class="jeepay-tip-text">选择[默认/H5/小程序]任意一种后不可修改，请谨慎选择。</p></div>
      </a-row>

      <!-- 只有新增 && 包含页面方式 && 查询到了支付地址时 -->
      <a-row v-if="vdata.saveObject.entryPage && vdata.saveObject.entryPage != 'h5'">
        <a-form-item v-if="vdata.isAdd && vdata.payHostUrl" label="二维码地址前缀" name="urlPlaceholder">
          <!-- 只读模式 -->
          <template v-if="vdata.modifyUrlPlaceholderFlag == false">
            <span>{{ getQrUrlView() }} </span> <a-button v-if="vdata.saveObject.entryPage != 'h5'" type="link" @click="vdata.modifyUrlPlaceholderFlag = !vdata.modifyUrlPlaceholderFlag">修改</a-button>
          </template>

          <!-- 修改模式 -->
          <template v-if="vdata.modifyUrlPlaceholderFlag == true">
            <span>{{ vdata.payHostUrl }}/cashier/</span> 
            &nbsp;<a-input v-model:value="vdata.saveObject.urlPlaceholder" placeHolder="自定义占位符" style="width: 130px;" />&nbsp;
            <span>/pages/hub/{{ vdata.saveObject.entryPage }} /</span> 
            
            <a-button type="link" @click="vdata.modifyUrlPlaceholderFlag = !vdata.modifyUrlPlaceholderFlag">确认</a-button>
          </template>
        </a-form-item>
        <div style="margin-left: 110px;margin-top: -50px;"><br><p class="jeepay-tip-text">若要使用小程序，请将该链接配置到微信小程序后台[开发管理-开发设置] 中的扫普通链接二维码打开小程序。若要配置到多个小程序需点击[修改]填写不同的占位符。</p></div>
      </a-row>
     
      
      <a-row>
        <a-form-item label="支付宝支付方式" name="alipayWayCode">
          <a-radio-group v-model:value="vdata.saveObject.alipayWayCode">
            <a-radio :value="'ALI_JSAPI'">ALI_JSAPI</a-radio>
            <a-radio :value="'ALI_WAP'">ALI_WAP</a-radio>
          </a-radio-group>
        </a-form-item>
        <div style="margin-left: -200px;margin-top: 10px;"><br><p class="jeepay-tip-text">仅H5呈现时生效</p></div>
      </a-row>
    </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc"><check-outlined />保存</a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>

import {API_URL_MCH_QR_CODE_LIST, API_URL_QRC_SHELL_LIST, $selectBatchIdDistinctCount, req, $getqrCodePaySiteUrl} from '@/api/manage'
import {defineProps, reactive, ref, getCurrentInstance, watch } from 'vue'
import ruleGenerator from '@/utils/ruleGenerator'
import {formatDate} from '@/utils/util'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties


// 定义组件参数
const props = defineProps({
  callbackFunc: {type: Function, default: () => {}}
})

// 定义ref对象
const infoFormModel = ref()

const saveRule = {
  addNum: [ruleGenerator.requiredInput('创建数量', 'number'), { type: 'number', max: 500, min: 1, message: '数量请介于1-500之间' }],
  batchId:[ruleGenerator.requiredInput('批次号', 'number'), { type: 'number', min: 1, max: 999999999999, message: '请输入正确的批次号，最长12位' }],
  appId: [{ required: true, message: '请选择应用', trigger: 'blur' }],
  fixedPayAmount: [{ required: true, message: '请输入固定金额', trigger: 'blur', type: 'number', min: 0.01 }],
}


const vdata : any = reactive({

  btnLoading: false,
  isAdd: true, // 新增 or 修改页面标志
  recordId: null, // 更新对象ID
  visible: false, // 是否显示弹层/抽屉
  saveObject: { urlPlaceholder: '' }, // 数据对象
  qrcShellList: [],

  payHostUrl: '', // 支付系统的域名
  modifyUrlPlaceholderFlag: false, // 是否修改模式

})


// 弹层打开事件
function show(recordId, mchNo) {

  // 查询支付系统的URL
  $getqrCodePaySiteUrl().then(res => {
    vdata.payHostUrl = res
  })

  // 查询全部模板信息
  req.list(API_URL_QRC_SHELL_LIST, {pageSize: -1}).then((res) => {
    vdata.qrcShellList = res.records
  })

  vdata.isAdd = !recordId
  vdata.saveObject = {addNum: 1, qrcState: 1, fixedFlag: 0, entryPage: 'default', alipayWayCode: 'ALI_JSAPI', urlPlaceholder: '' } // 重置清空
  vdata.modifyUrlPlaceholderFlag = false

  // 查询今天的总数量的批次号
  $selectBatchIdDistinctCount().then(res => {
      vdata.saveObject.batchId = parseInt(res)
  })


  // 重置表单验证规则
  if (infoFormModel.value) {
    infoFormModel.value.resetFields()
  }

  // 修改弹层
  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    vdata.recordId = recordId
    req.getById(API_URL_MCH_QR_CODE_LIST, recordId).then(res => {
      vdata.saveObject = res
      vdata.saveObject.fixedPayAmount = vdata.saveObject.fixedPayAmount / 100
      vdata.visible = true
    })
  } else {
    vdata.visible = true // 立马展示弹层信息
  }
}

// 点击 【保存】按钮的事件
function handleOkFunc(){

  vdata.btnLoading = true
  infoFormModel.value.validate().then(() => {

    if(vdata.isAdd){

      req.add(API_URL_MCH_QR_CODE_LIST, vdata.saveObject).then( res => reqSuccessFunc() ).finally(() => vdata.btnLoading = false)

    }else{

      req.updateById(API_URL_MCH_QR_CODE_LIST, vdata.recordId, vdata.saveObject).then( res => reqSuccessFunc() ).finally(() => vdata.btnLoading = false)
    }
  }).finally(() => vdata.btnLoading = false)

}

// 接口请求成功的处理函数
function reqSuccessFunc(){
  $infoBox.message.success( vdata.isAdd ? '新增成功' : '更新成功')
  vdata.visible = false
  props.callbackFunc() // 刷新列表
}


function onClose() {
  vdata.visible = false
}

function resetBatchId(){
  vdata.saveObject.batchId = parseInt(formatDate('YYMMDD00'))
}


// 避免输入特殊字符
watch( () => vdata.saveObject.urlPlaceholder ,(newVal, oldVal)=>{
  if(newVal && !/^[0-9a-zA-Z_-]+$/.test(newVal + '')){
    vdata.saveObject.urlPlaceholder = oldVal
  }
})


// 获取二维码的数据
function getQrUrlView(){

  if(!vdata.saveObject.entryPage){
    return '请选择扫码页面类型！'
  }

  return vdata.payHostUrl 
  + '/cashier' 
  + ( vdata.saveObject.urlPlaceholder ?  ('/' + vdata.saveObject.urlPlaceholder)  : '' )
  +  '/pages/hub/'+ vdata.saveObject.entryPage +'/'
}

// 切换到H5时清除自定义占位符、转换到非修改模式
function clearUrlPlaceholder(){
  if(vdata.saveObject.entryPage && vdata.saveObject.entryPage == 'h5') {
    vdata.modifyUrlPlaceholderFlag = false
    vdata.saveObject.urlPlaceholder = ''
  }
}
defineExpose({show})
</script>
